//
//  YFRefreshContrl.swift
//  微博
//
//  Created by 余仿 on 16/4/14.
//  Copyright © 2016年 YF. All rights reserved.
//

import UIKit

import SnapKit

enum YFRefreshState:Int{
    case Normal = 0 //普通状态
    case Pulling = 1 //下拉状态
    case Refreshing = 2 //正在刷新
}

class YFRefreshContrl: UIControl {


    /// 刷新控件的高度
    private let refreshViewHeight:CGFloat = 60

    private var scrollView:UIScrollView?

    var refreshState:YFRefreshState = .Normal{

        didSet{

            switch refreshState{

            case .Normal:
                tipLabel.text = "下拉刷新"

                indicater.stopAnimating()

                arrorView.hidden = false

                if oldValue == .Refreshing{

                    scrollView?.contentInset.top -= refreshViewHeight

                }

                UIView.animateWithDuration(1, animations: { () -> Void in

                    self.arrorView.transform = CGAffineTransformIdentity
                })
            case .Pulling:
                tipLabel.text = "准备刷新"
                UIView.animateWithDuration(1, animations: { () -> Void in

                    self.arrorView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
                tipLabel.text = "正在刷新"
                indicater.startAnimating()
                arrorView.hidden = true

                sendActionsForControlEvents(.ValueChanged)

                scrollView?.contentInset.top += refreshViewHeight
            }

        }
    }

    /// 箭头
    private lazy var arrorView:UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))

    /// 提示文字
    private lazy var tipLabel:UILabel = UILabel(title: "下拉刷新", fontSize: 16, fontColor: UIColor.blueColor())
    
    /// 菊花
    private lazy var indicater:UIActivityIndicatorView = UIActivityIndicatorView()

    override init(frame: CGRect) {

        let rect = CGRect(x: 0, y: -refreshViewHeight, width: screenWidth, height: refreshViewHeight)

        super.init(frame: rect)

        addSubview(arrorView)
        addSubview(tipLabel)
        addSubview(indicater)

        self.backgroundColor = UIColor.purpleColor()

        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func endRefreshing(){

        refreshState = .Normal
    }


    func setupUI(){

        tipLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
        }

        arrorView.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(tipLabel.snp_left)
            make.centerY.equalTo(self)
        }

        indicater.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrorView)
        }
    }


    //
    override func willMoveToSuperview(newSuperview: UIView?) {

        scrollView = newSuperview as? UIScrollView

        //监听scrollView的滚动--KVO

        scrollView!.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)

    }


    deinit{

        removeObserver(self, forKeyPath: "contentOffset")
    }


    //MARK:监听到变化后作出相应反应的方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {

        //下拉到某一位置改变文字和图片和菊花相应的状态
        let offsetY = scrollView!.contentOffset.y

        if scrollView!.dragging{
            //表示正在拖动
            if offsetY > -refreshViewHeight && refreshState == .Pulling{
                print("下拉刷新")
                refreshState = .Normal
            }else if( offsetY < -refreshViewHeight &&  refreshState == .Normal){
                print("准备刷新")
                refreshState = .Pulling
            }
        }else {

            if refreshState == .Pulling{

                refreshState = .Refreshing

                indicater.startAnimating()

                print("正在刷新")
                arrorView.hidden = true
            }
        }
    }

    //MARK:当状态改变,修改文本和图片的状态

    
}
